package com.aqie.appletserver.controller.baiduapi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.aqie.appletserver.bean.request.NewsRequest;
import com.aqie.appletserver.bean.response.CommonTextResponse;
import com.aqie.appletserver.bean.response.TextCensorResponse;
import com.aqie.appletserver.bean.response.TextCorrectionResponse;
import com.aqie.appletserver.common.response.ResponseModel;
import com.aqie.appletserver.service.AipNlpSingleton;
import com.aqie.appletserver.service.IBaiduApiService;
import com.baidu.aip.nlp.AipNlp;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
@RequestMapping("baidu/text")
@Slf4j
public class TextRecognitionController {
    @Value("${baidu.appID}")
    private String APP_ID;

    @Value("${baidu.apiKey}")
    private String API_KEY;

    @Value("${baidu.secretKey}")
    private String SECRET_KEY;

    @Autowired
    private IBaiduApiService baiduApiService;
    @PostMapping("textCensor")
    public ResponseModel<TextCensorResponse> textCensor(String text){
        TextCensorResponse textCensorResponse = baiduApiService.textCensor(text);
        return ResponseModel.success(textCensorResponse);
    }

    @PostMapping("textCorrect")
    public ResponseModel<TextCorrectionResponse> textCorrect(String text){
        TextCorrectionResponse textCorrectionResponse = baiduApiService.textCorrect(text);
        return ResponseModel.success(textCorrectionResponse );
    }

    // 自己实现新闻摘要
    @PostMapping("newsSummary")
    public ResponseModel<CommonTextResponse> newsSummary(@RequestBody NewsRequest request){
        CommonTextResponse commonResponse = baiduApiService.newsSummery(request);
        return ResponseModel.success(commonResponse);
    }

    // 使用百度sdk
    @PostMapping("newsSummary2")
    public ResponseModel<CommonTextResponse> newsSummary2(@RequestBody NewsRequest request){
        // 初始化一个AipNlp
        AipNlp client = AipNlpSingleton.getInstance();

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 调用接口
        JSONObject res = client.newsSummary(request.getContent(), request.getMaxSummaryLen(),new HashMap<>());
        CommonTextResponse response = JSON.parseObject(res.toString(), new TypeReference<CommonTextResponse>() {
        });
        return ResponseModel.success(response);
    }


}
